<?php

namespace App\Http\Controllers\Admin;

use App\Models\AuctionLog;
use App\Models\Goods;
use App\Models\GoodsDetail;
use App\Models\GoodsFile;
use App\Models\Type;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Validation\Rule;

class GoodsController extends Controller
{


    /**
     * 页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {


        return view('/admin/goods/index');
    }

    /**
     * 编辑
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit(Request $request)
    {
        $params = $request->only(['goods_id']);
        $validator = \Validator::make($params, [
            'goods_id' => 'required|exists:goods,id',
        ], [
            'goods_id.*' => '参数错误',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $data = Goods::find($request->goods_id);
        $detail = GoodsDetail::where('goods_id', $request->goods_id)->first();
        $type = Type::get();

        return view('admin/goods/edit', ['data' => $data, 'type' => $type, 'detail' => $detail]);
    }

    /**
     * 添加
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function add()
    {


        return view('admin/goods/add');
    }


    /**
     * 产品列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function data(Request $request)
    {
        $params = $request->only(['status', 'auction_status','searchParams']);
        $validator = \Validator::make($params, [
            'status' => [Rule::in([1, 2])],
            'auction_status' => [Rule::in([1, 2])]
        ], [
            'status.*' => '参数错误',
            'auction_status.*' => '参数错误',
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        $searchParams = json_decode($request->searchParams, true);
        //审核状态
        $status = $request->status;
        //拍卖状态
        $auctionStatus = $request->auction_status;
        //产品搜索
        $title = $searchParams['name'];
        //用户搜索
        $name = $request->name;
        //账号搜索
        $phone = $request->phone;

        $data = Goods::Status($status)
            ->select('goods.id', 'goods.title', 'users.name', 'users.phone', 'goods.price', 'goods.start_price', 'goods.scope_price', 'goods.status', 'goods.auction_status', 'goods.priorityer', 'goods.created_at')
            ->join('users', 'users.id', '=', 'goods.user_id')
            ->Title($title)
            ->UserName($name)
            ->Phone($phone)
            ->AuctionStatus($auctionStatus)
            ->paginate()->toArray();
        return $this->success(['data' => $data['data'], 'count' => $data['total'], 'code' => 0]);
//        return $this->success($list);
    }

    /**
     * 类型列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function typeList()
    {
        $list = Type::get();
        return $this->success($list);
    }


    /**
     * 产品详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request)
    {
        $params = $request->only(['goods_id']);
        $validator = \Validator::make($params, [
            'goods_id' => 'required|exists:goods,id',
        ], [
            'goods_id.*' => '参数错误',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        $goods = Goods::with('image', 'file')->find($request->goods_id);

        return $this->success($goods);
    }


    /**
     * 编辑/审核 产品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function saveGoods(Request $request)
    {
        $id = $request->goods_id;
        if ($request->status == 2) {
            $params = $request->only(['goods_id', 'title', 'type_id', 'publicity', 'publicity_day', 'auction', 'auction_day', 'cycle_price', 'delay_time',
                'introduce', 'notice', 'instructions', 'debt', 'status', 'message', 'debt_date']);
            $validator = \Validator::make($params, [
                'goods_id' => 'required|exists:goods,id',
                'title' => 'required|string|max:100',
                'type_id' => 'required|exists:types,id',

                'publicity' => 'required',//公示期
                'publicity_day' => 'required',//公示期

                'auction' => 'required',//开始拍卖日期
                'auction_day' => 'required',//拍卖竞价周期

                'delay_time' => 'required|numeric',//延时周期
                'introduce' => 'required',//介绍
                'notice' => 'required',//公告
                'instructions' => 'required',//竞买须知
                'status' => 'required',//审核状态
                'debt' => 'required',//债权金额
                'debt_date' => 'required',//债权期限
            ], [
                'goods_id.*' => '参数错误',
                'title.required' => '名称不能为空',
                'type_id.*' => '没有对应的类型',
                'title.max' => '名称长度最大为100个字符串',
                'publicity.required' => '公示日期不能为空',
                'publicity_day.required' => '公示期限不能为空',
                'auction.required' => '拍卖开始日期不能为空',
                'auction_day.required' => '竞价周期不能为空',
                'introduce.required' => '介绍不能为空',
                'delay_time.required' => '延时周期不能为空',
                'notice.required' => '竞买公告不能为空',
                'instructions.required' => '竞买须知不能为空',
                'status.required' => '审核状态不能为空',
                'debt.required' => '债权金额不能为空',
                'debt_date.required' => '债权期限不能为空'
            ]);
            if ($validator->fails()) {
                return $this->error($validator->errors()->first());
            }




            //计算折扣率
            //起拍价=  债权金额 - （债权金额*折扣率/一年的天数*剩余天数）


            $data = [
                'title' => $request->title,
                'type_id' => $request->type_id,
                'publicity' => $request->publicity,
                'publicity_day' => $request->publicity_day,
                'auction' => $request->auction,
                'auction_day' => $request->auction_day,
                'delay_time' => $request->delay_time,
                'introduce' => $request->introduce,
                'notice' => $request->notice,
                'instructions' => $request->instructions,
                'status' => $request->status,
                'message' => $request->message ?? '',
                'debt' => $request->debt,
                'debt_date' => $request->debt_date,
            ];

            $re = Goods::adminEdit($id, $data);
            if ($re) {
                return $this->success(['msg' => '修改成功']);
            }
            return $this->error('修改失败');
        }else{
            if ($request->status == 3 && $request->message == '') {

                return $this->error('请输入拒绝原因');
            }
            $goods = Goods::find($id);
            $goods->status = 3;
            $goods->message = $request->message;
            if ( $goods->save())
            {
                return $this->success(['msg' => '修改成功']);
            }
            return $this->error('修改失败');
        }


    }


    /**
     * 修改审核状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function saveGoodsStatus(Request $request)
    {
        $params = $request->only(['goods_id', 'status']);
        $validator = \Validator::make($params, [
            'goods_id' => 'required|exists:goods,id',
            'status' => ['required', Rule::in([1, 2, 3])]
        ], [
            'goods_id.*' => '参数错误',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        $goods_id = $request->goods_id;
        $status = $request->status;
        $re = Goods::saveStatus($goods_id, $status);
        if ($re) {
            return $this->success(['msg' => '修改成功']);
        }
        return $this->error('修改失败');
    }


    /**
     * 图片
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function image(Request $request)
    {

        $list = GoodsFile::where('goods_id', $request->id)->where('type', 1)->get();
        return view('admin/goods/image', ['data' => $list]);
    }

    /**
     * 附件
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function file(Request $request)
    {

        $list = GoodsFile::where('goods_id', $request->id)->where('type', 2)->get();

        return view('admin/goods/files', ['data' => $list]);
    }


    /**
     * 拍卖纪录
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function log(Request $request)
    {

        $id = $request->id;
        return view('admin/goods/log',['id'=>$id]);
    }

    /**
     * 拍卖纪录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */

    public function logList(Request $request)
    {
        $searchParams = json_decode($request->searchParams, true);
        $phone = $searchParams['phone'];
        $data = AuctionLog::where('goods_id', $request->id)
            ->where(function ($query)use($phone){
                if($phone){
                    $query->where('users.phone','like',"%$phone%");
                }
            })
            ->join('users','auction_logs.user_id','=','users.id')
            ->select('users.phone','auction_logs.price','auction_logs.created_at','auction_logs.id')
            ->orderBy('id','desc')
            ->paginate()->toArray();

        return $this->success(['data' => $data['data'], 'count' => $data['total'], 'code' => 0]);
    }

    /**
     * 删除记录
     * @return \Illuminate\Http\JsonResponse
     */
    public function  del(Request $request)
    {
        $params = $request->only(['id']);
        $validator = \Validator::make($params, [
            'id'=>'required|exists:auction_logs,id',
        ], [
            'id.*' => '参数错误',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        $admin = AuctionLog::find($request->id);

        if ( $admin->delete()) {
            return  $this->success(['msg'=>'删除成功']);
        }
        return  $this->error('删除失败');

    }

}
